package user;

import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @program: SpringBootDemos
 * @description: 公平锁
 * @author: Kangsen
 * @create: 2022-05-27 09:49
 **/
@Slf4j
public class FairLock {
    //公平锁
    ReentrantLock reentrantLock = new ReentrantLock(true);
    /**
     * 未拿到锁的线程阻塞排队,并且不允许插队
     */
    //食堂
    private class DiningRoom{
        public void getFood(){
            log.info("{} : 排队中",Thread.currentThread().getName());
            try {
                reentrantLock.lock();
                log.info(" {} : 打饭中",Thread.currentThread().getName());
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                reentrantLock.unlock();
            }
        }
    }

    @Test
    public void TestFairLock(){
        DiningRoom diningRoom = new DiningRoom();
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                diningRoom.getFood();
            },"编号"+(i+1)).start();
        }
    }
}
